import React, {useContext, useState} from "react"

// 定义上下文
const bgColorContext = React.createContext({
  color: 'red',
  name: 'xiatian'
})

export const ContextDemo = () => {

  const [bgColor, setBgColor] = useState({
    color: 'red',
    name: 'xiatian'
  })
  return (
    // <Father children={<Child bgColor={bgColor}/>}/>
    <>
      <input type="color" onChange={e => setBgColor({...bgColor, color:e.target.value})} />
      <bgColorContext.Provider value={bgColor}>
      <Father />
      </bgColorContext.Provider>
    </>
    
  )
}
const Father = () => {
  const bgColor = useContext(bgColorContext)
  return (
    <div style={{background: bgColor.color}}>
      <h2>Fater组件</h2>
      <Child />
    </div>
  )
}

const Child = ( ) => {
  return (
    // <div style={{background:bgColor }}>
    //   <h3>Child组件</h3>
    // </div>

    // 生产者消费者模式
    <>
      <bgColorContext.Consumer>
        {
          value => (
            <div style={{background:value.color}}>
              <h3>{value.name}生产消费者模式,接受到的值:{value.color}</h3>
            </div>
          )
        }
     </bgColorContext.Consumer>
    </>
    
  )
}